package cn.li.security.sms;

import cn.li.security.json.handle.AuthenticationFailJSONHandler;
import cn.li.security.json.handle.AuthenticationSuccessJSONHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.Assert;

/**
 * 配置类
 */
public class SmsAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    public static final String LOGIN_SMS_PATTERN = "/login/sms";
    @Setter
    private ISmsUserDetailService userDetailsService;

    @Setter
    private AuthenticationSuccessHandler successHandler;

    @Setter
    private AuthenticationFailureHandler failureHandler;

    @Setter
    private ObjectMapper objectMapper;

    @Setter
    private String pattern = LOGIN_SMS_PATTERN;

    //简化的构造器，默认使用JSON配置，这里完全可以按照filter来进行替换
    public SmsAuthenticationSecurityConfig(ISmsUserDetailService userDetailsService, ObjectMapper objectMapper) {
        this.userDetailsService = userDetailsService;
        this.objectMapper = objectMapper;
        this.successHandler = new AuthenticationSuccessJSONHandler(objectMapper);
        this.failureHandler = new AuthenticationFailJSONHandler(objectMapper);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsAuthenticationJSONFilter smsLoginFilter = new SmsAuthenticationJSONFilter(pattern,objectMapper);
        smsLoginFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsLoginFilter.setAuthenticationSuccessHandler(successHandler);
        smsLoginFilter.setAuthenticationFailureHandler(failureHandler);
        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
        smsAuthenticationProvider.setSmsUserService(userDetailsService);

        http    //将自定义的provider配置上去
                .authenticationProvider(smsAuthenticationProvider)
                // 将Filter添加到默认filter之前
                .addFilterBefore(smsLoginFilter, UsernamePasswordAuthenticationFilter.class)
                ;
    }
}
